package conf

import (
	"gitee.com/min65535/gotechback/techback/util/diagnostics"
	"github.com/spf13/viper"
	"strings"
)

// 连接超时
const CONN_TIMEOUT = 5

type (
	// MysqlDefaultConfig Mysql默认配置信息
	MysqlDefaultConfig struct {
		Host            string
		Port            int
		User            string
		Password        string
		DBName          string `mapstructure:"db_name"`
		Timeout         int    `mapstructure:"timeout"`       // 超时
		ReadTimeout     int    `mapstructure:"read_timeout"`  // 读超时
		WriteTimeout    int    `mapstructure:"write_timeout"` // 写超时
		MaxIdle         int    `mapstructure:"max_idle"`      // 最大空闲数
		MaxOpen         int    `mapstructure:"max_open"`      // 最大连接数
		ConnMaxLifetime int    `mapstructure:"max_lifetime"`  // 连接的最长时间
	}
	// RedisConfig Redis配置信息
	RedisConfig struct {
		Addr         string
		Password     string
		DB           int
		PoolSize     int `mapstructure:"pool_size"`
		ReadTimeout  int `mapstructure:"read_timeout"`
		WriteTimeout int `mapstructure:"write_timeout"`
	}
	// RdbConfig Rdb配置结构体
	RdbConfig struct {
		RDB *RedisConfig
	}

	// MysqlConfig 使用标签mapstructure:"tech_db"将MysqlConfig的TechDb字段映射为tech_db
	MysqlConfig struct {
		TechDb *MysqlDefaultConfig `mapstructure:"tech_db"`
	}
	// HTTPConfig HTTP配置信息
	HTTPConfig struct {
		Network string
		Addr    string
		Timeout int
	}
	// GrpcConfig Grpc配置信息
	GrpcConfig struct {
		Network string
		Addr    string
		Timeout int
		Log     bool
	}
	// ServerConfig 服务配置
	ServerConfig struct {
		HTTP *HTTPConfig `mapstructure:"http"`
		Grpc *GrpcConfig
	}
	// Config 配置信息
	Config struct {
		Server      *ServerConfig
		MySQL       *MysqlConfig
		Redis       *RdbConfig
		Diagnostics *diagnostics.DiagnosticsConfig
	}
)

func GetServerConfig(conf *Config) *ServerConfig {
	return conf.Server
}

func GetMysqlConfig(conf *Config) *MysqlConfig {
	return conf.MySQL
}

func GetRdbConfig(conf *Config) *RdbConfig {
	return conf.Redis
}

// InitConfig 初始化配置
func InitConfig(path string) (*Config, error) {
	v := viper.New()
	v.SetEnvPrefix(strings.ToUpper("gotechback"))
	v.SetConfigFile(path)
	v.SetConfigType("yaml")
	if err := v.ReadInConfig(); err != nil {
		return nil, err
	}
	var c = Config{}
	if err := v.Unmarshal(&c); err != nil {
		return nil, err
	}

	return &c, nil
}
